package com.john.exception.handler;

import com.john.Enum.ResultEnum;
import com.john.exception.CustomException;
import com.john.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 * 日期 2021/5/27 17:00
 * 创建者：john driver
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    // 自定义异常处理
    @ExceptionHandler(value = CustomException.class)
    public ResultVo customExceptionHandle(CustomException e){
        log.error("位置：{} -> 错误信息：{}",e.getMethod(),e.getResultEnum().getMessage());
        return ResultVo.error(e.getResultEnum());
    }
    // @valid 校验失败异常
    @ExceptionHandler(BindException.class)
    public ResultVo validExceptionHandler(BindException e){
        ResultVo resultVo = ResultVo.error(ResultEnum.BIND_ERROR);
        String message = e.getBindingResult()
                .getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(" and "));
        resultVo.setMessage(message);
        log.error("\n@valid 请求参数不合法：{}",message);
        return resultVo;
    }
    // @RequestParam校验异常
    @ExceptionHandler(ConstraintViolationException.class)
    public ResultVo requestParamExceptionHandler(BindException e){
        String message = e.getBindingResult()
                .getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(" and "));
        log.error("@RequestParam 请求参数不合法：{}",message);
        ResultVo resultVo = ResultVo.error(ResultEnum.REQUEST_PARAM_ERROR);
        resultVo.setMessage(message);
        return resultVo;
    }
    // @RequestBody上validate异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVo requestParamExceptionHandler(MethodArgumentNotValidException e){
        String message = e.getBindingResult()
                .getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(" and "));
        log.error("@RequestParam 请求参数不合法：{}",message);
        ResultVo resultVo = ResultVo.error(ResultEnum.REQUEST_PARAM_ERROR);
        resultVo.setMessage(message);
        return resultVo;
    }

    //未知异常处理
    @ExceptionHandler(value = Exception.class)
    public ResultVo exceptionHandle(Exception e){
        log.error("\n 未知异常：{}: {}",e.getClass(),e.getMessage());
        //e.printStackTrace();
        return ResultVo.error(ResultEnum.UNKNOWN_ERROR);
    }
}
